const express = require('express');
const historyService = require('../services/historyService');

const router = express.Router();

// 获取部署历史列表
router.get('/', async (req, res) => {
  try {
    const { limit = 20, offset = 0, status } = req.query;
    const result = await historyService.getHistory(parseInt(limit), parseInt(offset));
    
    // 如果指定了状态过滤
    if (status) {
      result.data = result.data.filter(record => record.status === status);
      result.total = result.data.length;
    }
    
    res.json({
      success: true,
      data: result.data,
      pagination: {
        total: result.total,
        limit: parseInt(limit),
        offset: parseInt(offset)
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取部署历史失败',
      error: error.message
    });
  }
});

// 获取特定部署记录
router.get('/:deployId', async (req, res) => {
  try {
    const { deployId } = req.params;
    const record = await historyService.getRecord(deployId);
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '部署记录不存在'
      });
    }
    
    res.json({
      success: true,
      data: record
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取部署记录失败',
      error: error.message
    });
  }
});

// 删除部署记录
router.delete('/:deployId', async (req, res) => {
  try {
    const { deployId } = req.params;
    await historyService.deleteRecord(deployId);
    
    res.json({
      success: true,
      message: '部署记录已删除'
    });
  } catch (error) {
    if (error.message.includes('不存在')) {
      res.status(404).json({
        success: false,
        message: error.message
      });
    } else {
      res.status(500).json({
        success: false,
        message: '删除部署记录失败',
        error: error.message
      });
    }
  }
});

// 清空所有历史记录
router.delete('/', async (req, res) => {
  try {
    await historyService.clearHistory();
    
    res.json({
      success: true,
      message: '所有历史记录已清空'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '清空历史记录失败',
      error: error.message
    });
  }
});

// 获取统计信息
router.get('/stats/summary', async (req, res) => {
  try {
    const stats = await historyService.getStatistics();
    
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取统计信息失败',
      error: error.message
    });
  }
});

// 批量操作
router.post('/batch', async (req, res) => {
  try {
    const { action, deployIds } = req.body;
    
    if (!action || !Array.isArray(deployIds)) {
      return res.status(400).json({
        success: false,
        message: '请求参数不正确'
      });
    }
    
    const results = [];
    
    switch (action) {
      case 'delete':
        for (const deployId of deployIds) {
          try {
            await historyService.deleteRecord(deployId);
            results.push({ deployId, success: true });
          } catch (error) {
            results.push({ deployId, success: false, error: error.message });
          }
        }
        break;
        
      default:
        return res.status(400).json({
          success: false,
          message: '不支持的批量操作'
        });
    }
    
    const successCount = results.filter(r => r.success).length;
    const failCount = results.length - successCount;
    
    res.json({
      success: failCount === 0,
      message: `批量操作完成：成功 ${successCount} 个，失败 ${failCount} 个`,
      results
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '批量操作失败',
      error: error.message
    });
  }
});

module.exports = router;